import Vue from 'vue'
// import { login, getInfo, logout } from '@/api/login'
import { login, getStoreList, getStoreListByName } from '@/api/login'
import { ACCESS_TOKEN } from '@/store/mutation-types'
import { welcome } from '@/utils/util'
import { roleObj } from '@/mock/services/permission'
import md5 from 'md5'
import { Base64 } from 'js-base64'
import Cookies from 'js-cookie'

const user = {
  state: {
    token: '',
    name: '',
    welcome: '',
    avatar: '',
    roles: [],
    info: {},
    STORE_ID: '',
    STORE_LIST: [],
    OPERATOR_TYPE: '',
    storeRefreshTime: '' // 门店刷新时间
  },

  mutations: {
    SET_TOKEN: (state, token) => {
      state.token = token
    },
    SET_NAME: (state, { name, welcome }) => {
      state.name = name
      state.welcome = welcome
    },
    SET_AVATAR: (state, avatar) => {
      state.avatar = avatar
    },
    SET_ROLES: (state, roles) => {
      state.roles = roles
    },
    SET_INFO: (state, info) => {
      state.info = info
    },
    SET_STORE_ID: (state, data) => {
      Vue.ls.set('STORE_ID', data, 7 * 24 * 60 * 60 * 1000)
      state.STORE_ID = data
    },
    SET_STORE_LIST: (state, data) => {
      Vue.ls.set('STORE_LIST', data, 7 * 24 * 60 * 60 * 1000)
      state.STORE_LIST = data
    },
    SET_OPERATOR_TYPE: (state, data) => {
      Vue.ls.set('OPERATOR_TYPE', data, 7 * 24 * 60 * 60 * 1000)
      state.OPERATOR_TYPE = data
    },
    SET_STORE_REFRESH_TIME: (state, data) => {
      state.storeRefreshTime = data
    }
  },

  actions: {
    // 登录
    Login ({ commit }, userInfo) {
      return new Promise((resolve, reject) => {
        login(userInfo)
          .then(res => {
            if (res.code === 2021) {
              resolve(res)
            } else {
              const result = res.data
              const avatar = '/avatar2.png'
              const hoperators = result.hoperators
              const StoresList = result.StoresList
              const md5Msg = md5(`juliwei${hoperators.jyrlxdh}`)
              const tag = Base64.encode(`${md5Msg} - ${new Date().getTime()}`)
              Vue.ls.set(ACCESS_TOKEN, hoperators.token, 7 * 24 * 60 * 60 * 1000)
              Vue.ls.set('userInfo', hoperators, 7 * 24 * 60 * 60 * 1000)
              Vue.ls.set('VERSION', '2.0', 7 * 24 * 60 * 60 * 1000)
              Vue.ls.set('JULIWEI-TAG', tag, 7 * 24 * 60 * 60 * 1000)
              commit('SET_INFO', hoperators)
              commit('SET_STORE_ID', StoresList[0].storesId)
              commit('SET_OPERATOR_TYPE', StoresList[0].jylx)
              commit('SET_TOKEN', hoperators.token)
              commit('SET_NAME', { name: hoperators.glrxm, welcome: welcome() })
              commit('SET_AVATAR', avatar)
              commit('SET_STORE_LIST', StoresList)
              Cookies.set('JLW_VERIFIED', null)
              resolve(result)
            }
          })
          .catch(error => {
            reject(error)
          })
      })
    },

    // 获取用户信息
    GetInfo ({ commit }) {
      return new Promise((resolve, reject) => {
        // roleObj.permissions.push({
        //   'roleId': 'admin',
        //   'permissionId': 'support',
        //   'permissionName': '超级模块',
        //   'actions': '[{"action":"add","defaultCheck":false,"describe":"新增"},{"action":"import","defaultCheck":false,"describe":"导入"},{"action":"get","defaultCheck":false,"describe":"详情"},{"action":"update","defaultCheck":false,"describe":"修改"},{"action":"delete","defaultCheck":false,"describe":"删除"},{"action":"export","defaultCheck":false,"describe":"导出"}]',
        //   'actionEntitySet': [{
        //     'action': 'add',
        //     'describe': '新增',
        //     'defaultCheck': false
        //   }, {
        //     'action': 'import',
        //     'describe': '导入',
        //     'defaultCheck': false
        //   }, {
        //     'action': 'get',
        //     'describe': '详情',
        //     'defaultCheck': false
        //   }, {
        //     'action': 'update',
        //     'describe': '修改',
        //     'defaultCheck': false
        //   }, {
        //     'action': 'delete',
        //     'describe': '删除',
        //     'defaultCheck': false
        //   }, {
        //     'action': 'export',
        //     'describe': '导出',
        //     'defaultCheck': false
        //   }],
        //   'actionList': null,
        //   'dataAccess': null
        // })
        const result = {
          role: roleObj
        }
        if (result.role && result.role.permissions.length > 0) {
          const role = result.role
          role.permissions = result.role.permissions
          role.permissions.map(per => {
            if (per.actionEntitySet != null && per.actionEntitySet.length > 0) {
              const action = per.actionEntitySet.map(action => {
                return action.action
              })
              per.actionList = action
            }
          })
          role.permissionList = role.permissions.map(permission => {
            return permission.permissionId
          })
          commit('SET_ROLES', result.role)
          resolve({ result })
        } else {
          reject(new Error('getInfo: roles must be a non-null array !'))
        }
      })
    },

    // 登出
    Logout ({ commit, state }) {
      return new Promise(resolve => {
        commit('SET_TOKEN', '')
        commit('SET_ROLES', [])
        commit('SET_INFO', '')
        commit('SET_STORE_ID', '')
        commit('SET_STORE_LIST', '')
        commit('SET_OPERATOR_TYPE', '')
        Vue.ls.remove(ACCESS_TOKEN)
        Vue.ls.remove('userInfo')
        Vue.ls.remove('STORE_LIST')
        Vue.ls.remove('STORE_ID')
        Vue.ls.remove('OPERATOR_TYPE')
        Vue.ls.remove('VERSION')
        Vue.ls.remove('JULIWEI-TAG')
        commit('SET_STORE_REFRESH_TIME', '')
        sessionStorage.setItem('orderListMenu', '')
        resolve()
        // logout(state.token).then(() => {
        //   resolve()
        // }).catch(() => {
        //   resolve()
        // })
      })
    },
    // 获取门店列表
    GetStoreList ({ commit }, data) {
      return new Promise((resolve, reject) => {
        getStoreList(data)
          .then(res => {
            // 方法1
            // const StoresList = res.data.filter((e, index, a) => (a.map(b => b['storesId']).indexOf(e['storesId'])) === index)
            // 方法2
            const set = new Set()
            const StoresList = res.data.filter(item => {
              const isTrue = set.has(item['storesId'])
              set.add(item['storesId'])
              return !isTrue
            })
            // 方法3
            // const StoresList = res.data.reduce((acc, cur) => {
            //   let isShow = acc.find(item => item['storesId'] === cur['storesId'])
            //   if (!isShow) {
            //     return acc.concat([cur])
            //   } else {
            //     return acc
            //   }
            // }, [])
            // 方法4
            // const StoresList = [...new Set(res.data.map(item => item['storesId']))].map(e => {
            //   return res['data'].find(d => d['storesId'] === e)
            // })
            resolve(StoresList)
          })
          .catch(error => {
            reject(error)
          })
      })
    },

    // 通过名称获取门店列表
    getStoreListByName ({ commit }, data) {
      return new Promise((resolve, reject) => {
        getStoreListByName(data).then(res => {
          const StoresList = res.data
          resolve(StoresList)
        }).catch(error => {
          reject(error)
        })
      })
    }
  }
}

export default user
